package com.starblink.mine.personhome.ui.post.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.starblink.android.basic.animators.FadeInAnimator
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.utils.*
import com.starblink.android.basic.ext.ApolloModelExt.isPostOpen
import com.starblink.android.basic.ext.ApolloValSetExt
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.LikePostEvent
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.mine.R
import com.starblink.mine.databinding.FragmentPostBinding
import com.starblink.mine.databinding.ItemPostCreateBinding
import com.starblink.mine.databinding.ItemSimplePostCardBinding
import com.starblink.mine.personhome.ui.SharedViewModel
import com.starblink.mine.personhome.ui.like.ui.LikeVM
import com.starblink.mine.personhome.ui.post.ui.bean.RvCreatePostEntry
import com.starblink.rocketreserver.FetchPublishPostsByAccountIdQuery.FetchPublishPostsByAccountId
import com.starblink.rocketreserver.fragment.AccountF
import com.starblink.rocketreserver.fragment.PostF
import kotlinx.coroutines.launch

class PostFragment : BaseTVMFragment<FragmentPostBinding, PostVM>() {
    var accountDeleted: Boolean = false
    var pageType: Int = MineManager.PersonHomePageType.MINE
    private val sharedViewModel by activityViewModels<SharedViewModel>()

    companion object {
        private const val TAG = "PostFragment"
        fun newInstance(pageType: Int, accountId: String, accountDeleted: Boolean) =
            PostFragment().apply {
                arguments = bundleOf(
                    MineManager.KEY_PAGE_TYPE to pageType,
                    MineManager.KEY_USER_ID to accountId,
                    MineManager.KEY_ACCOUNT_DELETED to accountDeleted
                )
            }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentPostBinding {
        return FragmentPostBinding.inflate(inflater, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SKLogger.e("dss", "PostFragment-onCreate")
    }

    /**
     * 初始化数据
     */
    override fun initData() {
        arguments?.run {
            pageType = getInt(MineManager.KEY_PAGE_TYPE, MineManager.PersonHomePageType.MINE)
            getString(MineManager.KEY_USER_ID)?.let {
                viewModel.accountId = it
            }
            accountDeleted = getBoolean(MineManager.KEY_ACCOUNT_DELETED, false)
        }
    }

    override fun initView(view: View) {
        super.initView(view)
        // 客态-如果账户已删除，仅显示Empty页面即可
        if (pageType == MineManager.PersonHomePageType.OTHER_USER && accountDeleted) {
            viewBinding.page.onEmpty {
                val tvMsg1 = findViewById<TextView>(R.id.msg2)
                tvMsg1.text = "No Posts"
            }
            return
        }

        //初始化列表相关
        viewBinding.rv.itemAnimator = FadeInAnimator()
        viewBinding.rv.staggered(2).defaultDividerStagger().setup {
            addType<FetchPublishPostsByAccountId, ItemSimplePostCardBinding>(it)
            addType<RvCreatePostEntry, ItemPostCreateBinding>(it)

            onBind {
                when (val viewBinding = getBinding<ViewBinding>()) {
                    is ItemSimplePostCardBinding -> {
                        // 列表项类型=Post卡片
                        val post = getModel<FetchPublishPostsByAccountId>().postF

                        // 数据Post和PostCardView控件绑定，设置点击事件
                        viewBinding.card.bindPost(
                            post,
                            modelPosition,
                            false,
                            spmPageValue = SpmPageDef.MinePostTabView
                        ) {
                            commContext().navigationTo(if (post.contentType == "1") RoutePage.Post.PAGE_PIC else RoutePage.PostVideo.PAGE_VIDEO) {
                                withString(RoutePage.Post.POST_ID, post.id)
                                withInt(RoutePage.Post.ARG_SCENE, RoutePage.Post.SCENE.ME.value)
                                withObject(RoutePage.Post.POST, post)
                            }
                        }
                    }
                    is ItemPostCreateBinding -> {
                        // 列表项类型=创建Post按钮
                    }
                }
            }

//            onClick(R.id.root) {
//                toast("创建post")
//            }
        }

        viewBinding.page.onEmpty {
            val tvMsg1 = findViewById<TextView>(R.id.msg2)
            if (it is AccountF) {
                if (it.deleted == true) {
                    tvMsg1.text = "No Posts"
                } else if (!it.isPostOpen()) {
                    tvMsg1.text = "The posts is not visible."
                }
            } else {
                tvMsg1.text = "No posts yet."
            }
        }

        viewBinding.page.onRefresh {
            viewModel.getPublishedPosts(refresh = true)
        }
        viewBinding.page.onLoadMore {
            viewModel.getPublishedPosts(refresh = false)
        }

//        // 主态-默认显示创建Post列表项
//        if (pageType == MineManager.PersonHomePageType.MINE) {
//            val list = ArrayList<Any>()
//            list.add(RvCreatePostEntry())
//            viewBinding.rv.addModels(list)
//            viewBinding.page.showContent(false)
//        }
    }

    override fun startObserve() {
        iniEventListener()

        // 客态-如果账户已删除，仅显示Empty页面即可
        if (pageType == MineManager.PersonHomePageType.OTHER_USER && accountDeleted) {
            viewBinding.page.showEmpty()
            return
        }

        sharedViewModel.userInfoLiveData.observe(this) {
            // 客态-用户信息加载完毕
            // 如果用户账户已删除或用户Posts不允许查看，显示错误提示
            // 否则，触发刷新，加载列表数据
            if (it.deleted == true || !it.isPostOpen()) {
                viewBinding.page.showEmpty(it)
                viewBinding.page.setEnableRefresh(false)
                viewBinding.page.setEnableLoadMore(false)
            } else {
                viewBinding.page.refresh()
            }
        }

        viewModel.listResponseLiveData.observe(this) {
            if (viewBinding.rv.models.isNullOrEmpty() || it.refresh) {
                // 刷新或页面销毁恢复
                val list = ArrayList<Any>(LikeVM.PAGE_SIZE * 2)
//                if (pageType == MineManager.PersonHomePageType.MINE) {
//                    list.add(RvCreatePostEntry())
//                }
                list.addAll(it.totalList)
                viewBinding.page.addData(list) {
                    it.totalList.size >= viewModel.curPageNo * LikeVM.PAGE_SIZE
                }
            } else {
                // 加载更多
                viewBinding.page.addData(it.pageList) {
                    it.pageList.size >= LikeVM.PAGE_SIZE
                }
            }
        }
        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError()
                }
            }
        }

        if (pageType == MineManager.PersonHomePageType.MINE) {
            // 主态-仅加载列表数据
            viewBinding.page.refresh()
        } else {
            // 客态-仅显示加载中，需要等待用户信息加载完毕
            viewBinding.page.showLoading(refresh = false)
        }
    }

    private fun iniEventListener() {
        // 监听点赞发布事件
        FlowBus.with<LikePostEvent>(FlowConst.LIKE_POST_EVENT).register(this) {
//            SKLogger.e("dss", "PostFragment-LIKE_POST_EVENT")
            // 仅当发布用户是当前用户时，更新点赞状态
            if (viewModel.accountId == it.posterId && it.postId.isNullOrEmpty()
                    .not() && viewModel.listResponseLiveData.value != null
            ) {
                lifecycleScope.launch {
                    for ((index, publishPost) in viewModel.listResponseLiveData.value!!.totalList.withIndex()) {
                        val post = publishPost.postF
                        if (it.postId == post.id && it.like != post.liked) {
//                            SKLogger.e("dss", "PostFragment-发现Post要修改")
                            ApolloValSetExt.setApolloVal<PostF>(post, "liked", it.like)
                            ApolloValSetExt.setApolloVal<PostF>(post, "likeNumbers", it.likeCount)
                            viewBinding.rv.bindingAdapter.notifyItemChanged(index)
                            break
                        }
                    }
                }
            }
        }
    }
}